package com.renke.server;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

/**
 * @Description
 * @Auther Z.R.K
 * @Date 2020/12/7 15:24
 **/
@Slf4j
public class NIOThread implements Runnable {
    LinkedList<SocketChannel> clients = new LinkedList<>();

    public void addClient(SocketChannel socketChannel) {
        clients.add(socketChannel);
    }

    @Override
    public void run() {
        while(true){
            try {
                ByteBuffer byteBuffer = ByteBuffer.allocate(8);
                for (SocketChannel channel : clients) {
                    int num = channel.read(byteBuffer);
                    if (num > 0) {
                        // 将position替换为limit，同时将position置零
                        byteBuffer.flip();
                        // 创建读到的文本长度字节数组
                        byte[] aa = new byte[byteBuffer.limit()];
                        // 获取字节数据长度的数据，存入数组中
                        byteBuffer.get(aa);
                        String str = new String(aa);
                        log.info("read client {} {} msg : {}", channel.socket().getInetAddress().getHostAddress(), channel.socket().getPort(), str);
                        byteBuffer.clear();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
